package com.atguigu.gulimall.order.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.to.OrderTo;
import com.atguigu.common.to.SeckillOrderTo;
import com.atguigu.common.utils.R;
import com.atguigu.common.vo.HasStockVo;
import com.atguigu.common.vo.MemberEntity;
import com.atguigu.gulimall.order.constant.OrderConstant;
import com.atguigu.gulimall.order.entity.OrderItemEntity;
import com.atguigu.gulimall.order.entity.PaymentInfoEntity;
import com.atguigu.gulimall.order.enume.OrderStatusEnum;
import com.atguigu.gulimall.order.exception.NoStockException;
import com.atguigu.gulimall.order.feign.CartFeign;
import com.atguigu.gulimall.order.feign.MemberFeign;
import com.atguigu.gulimall.order.feign.ProductFeign;
import com.atguigu.gulimall.order.feign.WareFeign;
import com.atguigu.gulimall.order.interceptor.OrderInterceptor;
import com.atguigu.gulimall.order.service.OrderItemService;
import com.atguigu.gulimall.order.service.PaymentInfoService;
import com.atguigu.gulimall.order.vo.*;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.order.dao.OrderDao;
import com.atguigu.gulimall.order.entity.OrderEntity;
import com.atguigu.gulimall.order.service.OrderService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;


@Service("orderService")
public class OrderServiceImpl extends ServiceImpl<OrderDao, OrderEntity> implements OrderService {
    @Autowired
    private MemberFeign memberFeign;
    @Autowired
    private CartFeign cartFeign;
    @Autowired
    private WareFeign wareFeign;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private ThreadPoolExecutor threadPoolExecutor;
    @Autowired
    private ProductFeign productFeign;
    @Autowired
    private OrderService orderService;
    @Autowired
    private OrderItemService orderItemService;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private PaymentInfoService paymentInfoService;
    public static final ThreadLocal<OrderSubmitVo> threadLocal = new ThreadLocal<>();
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public OrderConfirmVo toTrade() throws ExecutionException, InterruptedException {
        OrderConfirmVo orderConfirmVo = new OrderConfirmVo();

        MemberEntity memberEntity = OrderInterceptor.threadLocal.get();
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();

        CompletableFuture<Void> addressCompletableFuture = CompletableFuture.runAsync(() -> {
            RequestContextHolder.setRequestAttributes(requestAttributes);
            //远程查询所有用户地址信息
            R r = memberFeign.getAddress(memberEntity.getId());
            if (r.getCode() == 0) {
                List<MemberAddressVo> memberReceiveAddress = r.getData("data", new TypeReference<List<MemberAddressVo>>() {
                });
                orderConfirmVo.setMemberAddressVos(memberReceiveAddress);
            }
        },threadPoolExecutor);


        CompletableFuture<Void> voidCompletableFuture = CompletableFuture.runAsync(() -> {
            RequestContextHolder.setRequestAttributes(requestAttributes);
            //远程查询所有选中的购物车
            R checkedCart = cartFeign.getCheckedCart();
            if (checkedCart.getCode() == 0) {
                List<OrderItemVo> data = checkedCart.getData("data", new TypeReference<List<OrderItemVo>>() {
                });
                orderConfirmVo.setItems(data);
            }

        },threadPoolExecutor).thenRunAsync(() -> {
            List<OrderItemVo> data = orderConfirmVo.getItems();
            List<Long> skuIds = data.stream().map(item -> {
                return item.getSkuId();
            }).collect(Collectors.toList());
            if (skuIds != null) {
                //远程查询库存
                R hasStock = wareFeign.getHasStock(skuIds);
                List<HasStockVo> vos = hasStock.getData("data", new TypeReference<List<HasStockVo>>() {
                });
                Map<Long, Boolean> map = vos.stream().collect(Collectors.toMap(HasStockVo::getSkuId, HasStockVo::getHasStock));
                orderConfirmVo.setStocks(map);
            }
        },threadPoolExecutor);
        //查询用户积分
        orderConfirmVo.setIntegration(memberEntity.getIntegration());

        //给前端发送令牌,确保订单重复提交
        String token = UUID.randomUUID().toString().replace("-", "");
        stringRedisTemplate.opsForValue().set(OrderConstant.ORDER_TOKEN_REDIS+memberEntity.getId(),token,30, TimeUnit.MINUTES);
        orderConfirmVo.setOrderToken(token);
        CompletableFuture.allOf(addressCompletableFuture,voidCompletableFuture).get();
        return orderConfirmVo;
    }

    @Override
    //@GlobalTransactional
    @Transactional
    //假异常（执行完成，但是返回超时）
    //远程服务下面出现异常
    public OrderSubmitResponseVo submitOrder(OrderSubmitVo orderSubmitVo)throws NoStockException {
        OrderSubmitResponseVo responseVo = new OrderSubmitResponseVo();
        //防止订单重复提交
        String orderToken = orderSubmitVo.getOrderToken();
        //获取当前登录用户
        MemberEntity memberEntity = OrderInterceptor.threadLocal.get();
        //使用lua脚本保证获取、比较、删除的一致性
        String luaScript = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
        Long result = stringRedisTemplate.execute(new DefaultRedisScript<Long>(luaScript, Long.class), Arrays.asList(OrderConstant.ORDER_TOKEN_REDIS + memberEntity.getId()), orderToken);
        if(result==0){
            //令牌验证失败
            responseVo.setCode(1);
            return responseVo;
        }else {
            //令牌验证成功
            //构建订单数据和订单项数据
            threadLocal.set(orderSubmitVo);
            CreateOrderVo createOrderVo =  createOrderVO();
            //验证价格
            BigDecimal payPrice = orderSubmitVo.getPayPrice();
            BigDecimal payAmount = createOrderVo.getOrderEntity().getPayAmount();
            if(Math.abs(payPrice.subtract(payAmount).doubleValue())<0.01){
                //向数据库中保存订单和订单项
                saveOrder(createOrderVo);
                //锁定库存
                LockStockVo lockStockVo = new LockStockVo();
                lockStockVo.setOrderSn(createOrderVo.getOrderEntity().getOrderSn());
                List<OrderItemVo> orderItemVos = createOrderVo.getOrderItemEntityList().stream().map(item -> {
                    OrderItemVo orderItemVo = new OrderItemVo();
                    orderItemVo.setSkuId(item.getSkuId());
                    orderItemVo.setAmount(item.getSkuQuantity());
                    orderItemVo.setTitle(item.getSkuName());
                    return orderItemVo;
                }).collect(Collectors.toList());
                lockStockVo.setOrderItemVoList(orderItemVos);

                R r = wareFeign.lockStock(lockStockVo);

                if(r.getCode()==0){
                    //锁定库存成功
                    responseVo.setCode(0);
                    responseVo.setOrder(createOrderVo.getOrderEntity());

                    //订单创建完成，发送消息，一定时间后未支付自动解锁
                    rabbitTemplate.convertAndSend("order-event-exchange","order.create.order",createOrderVo.getOrderEntity());
                    //TODO删除购物车数据

                    return responseVo;
                }else {
                    //库存锁定失败
                    throw new NoStockException(0L);

                }
            }else {
                responseVo.setCode(2);
                return responseVo;
            }
        }
    }

    @Override
    public OrderEntity getOrderEntityByOrderSn(String orderSn) {
        OrderEntity orderEntity = orderService.getOne(new QueryWrapper<OrderEntity>().eq("order_sn", orderSn));
        return orderEntity;
    }

    @Override
    public void closeOrder(OrderEntity orderEntity) {
        OrderEntity entity = orderService.getOne(new QueryWrapper<OrderEntity>().eq("order_sn", orderEntity.getOrderSn()));
        if(entity.getStatus().equals(OrderStatusEnum.CREATE_NEW.getCode())){
            OrderEntity entity1 = new OrderEntity();
            entity1.setId(orderEntity.getId());
            entity1.setStatus(OrderStatusEnum.CANCLED.getCode());

            orderService.updateById(entity1);

            //发消息给mq，防止订单收到消息时间比库存接受到消息时间长
            OrderTo orderTo = new OrderTo();
            BeanUtils.copyProperties(orderEntity,orderTo);
            rabbitTemplate.convertAndSend("stock-event-exchange","stock.release",orderTo);
        }
    }

    @Override
    public PayVo getPayVoWithOrderSn(String orderSn) {
        OrderEntity order_sn = orderService.getOne(new QueryWrapper<OrderEntity>().eq("order_sn", orderSn));
        List<OrderItemEntity> order_sn1 = orderItemService.list(new QueryWrapper<OrderItemEntity>().eq("order_sn", orderSn));
        PayVo payVo = new PayVo();
        payVo.setOut_trade_no(orderSn);
        BigDecimal bigDecimal = order_sn.getPayAmount().setScale(2, RoundingMode.UP);
        payVo.setTotal_amount(bigDecimal.toString());
        payVo.setSubject(order_sn1.get(0).getSpuName());
        payVo.setBody(order_sn1.get(0).getSkuAttrsVals());
        return payVo;
    }

    @Override
    public PageUtils getOrderAndOrderItemList(Map<String, Object> params) {
        MemberEntity memberEntity = OrderInterceptor.threadLocal.get();
        Long memberEntityId = memberEntity.getId();


        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>().eq("member_id",memberEntityId).orderByDesc("create_time")
        );
        List<OrderEntity> orderEntityList = page.getRecords().stream().map(orderEntity -> {
            String orderSn = orderEntity.getOrderSn();
            List<OrderItemEntity> orderItemEntities = orderItemService.list(new QueryWrapper<OrderItemEntity>().eq("order_sn", orderSn));
            orderEntity.setOrderItemEntityList(orderItemEntities);
            return orderEntity;
        }).collect(Collectors.toList());

        page.setRecords(orderEntityList);

        return new PageUtils(page);
    }

    @Override
    @Transactional
    public String updateOrderStatus(PayAsyncVo payAsyncVo) {

        PaymentInfoEntity paymentInfoEntity = new PaymentInfoEntity();
        paymentInfoEntity.setOrderSn(payAsyncVo.getOut_trade_no());
        paymentInfoEntity.setAlipayTradeNo(payAsyncVo.getTrade_no());
        paymentInfoEntity.setCallbackTime(payAsyncVo.getNotify_time());
        paymentInfoEntity.setCreateTime(new Date());
        paymentInfoEntity.setPaymentStatus(payAsyncVo.getTrade_status());
        paymentInfoEntity.setTotalAmount(new BigDecimal(payAsyncVo.getBuyer_pay_amount()));
        paymentInfoService.save(paymentInfoEntity);

        if("TRADE_FINISHED".equals(payAsyncVo.getTrade_status()) || "TRADE_SUCCESS".equals(payAsyncVo.getTrade_status())){
            this.update(new UpdateWrapper<OrderEntity>().eq("order_sn",payAsyncVo.getOut_trade_no()).set("status",OrderStatusEnum.PAYED.getCode()));
        }

        return "success";
    }

    @Override
    public void createOrder(SeckillOrderTo orderTo) {
        //TODO 保存订单信息
        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setOrderSn(orderTo.getOrderSn());
        orderEntity.setMemberId(orderTo.getMemberId());
        orderEntity.setCreateTime(new Date());
        BigDecimal totalPrice = orderTo.getSeckillPrice().multiply(BigDecimal.valueOf(orderTo.getNum()));
        orderEntity.setPayAmount(totalPrice);
        orderEntity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());

        //保存订单
        this.save(orderEntity);

        //保存订单项信息
        OrderItemEntity orderItem = new OrderItemEntity();
        orderItem.setOrderSn(orderTo.getOrderSn());
        orderItem.setRealAmount(totalPrice);
        orderItem.setSkuQuantity(orderTo.getNum());

        //保存商品的spu信息
        R spuInfo = productFeign.getSpuEntityWithSkuId(orderTo.getSkuId());
        SpuInfoVo spuInfoData = spuInfo.getData("data", new TypeReference<SpuInfoVo>() {
        });
        orderItem.setSpuId(spuInfoData.getSpuId());
        orderItem.setSpuName(spuInfoData.getSpuName());
        orderItem.setSpuBrand(spuInfoData.getBrandName());
        orderItem.setCategoryId(spuInfoData.getCatalogId());

        //保存订单项数据
        orderItemService.save(orderItem);
    }

    private void saveOrder(CreateOrderVo createOrderVo) {
        OrderEntity orderEntity = createOrderVo.getOrderEntity();
        orderEntity.setCreateTime(new Date());
        orderEntity.setModifyTime(new Date());
        orderService.save(orderEntity);
        orderItemService.saveBatch(createOrderVo.getOrderItemEntityList());
    }

    //构建订单数据和订单项数据
    private CreateOrderVo createOrderVO() {
        CreateOrderVo createOrderVo = new CreateOrderVo();
        //创建订单号
        String timeId = IdWorker.getTimeId();
        //构建订单数据
        OrderEntity orderEntity = createOrderEntity(timeId);
        createOrderVo.setOrderEntity(orderEntity);
        //构建订单项数据
        List<OrderItemEntity> itemEntityList = createOrderItemEntities(timeId);
        createOrderVo.setOrderItemEntityList(itemEntityList);
        //设置订单未设置完整的优惠信息和金额
        computePrice(orderEntity,itemEntityList);
        //设置删除状态
        orderEntity.setDeleteStatus(0);

        createOrderVo.setOrderItemEntityList(itemEntityList);
        createOrderVo.setOrderEntity(orderEntity);
        return createOrderVo;
    }

    private void computePrice(OrderEntity orderEntity, List<OrderItemEntity> orderItemEntities) {
        //总价
        BigDecimal total = new BigDecimal("0.0");
        //优惠价
        BigDecimal coupon = new BigDecimal("0.0");
        BigDecimal intergration = new BigDecimal("0.0");
        BigDecimal promotion = new BigDecimal("0.0");

        //积分、成长值
        Integer integrationTotal = 0;
        Integer growthTotal = 0;

        //订单总额，叠加每一个订单项的总额信息
        for (OrderItemEntity orderItem : orderItemEntities) {
            //优惠价格信息
            coupon = coupon.add(orderItem.getCouponAmount());
            promotion = promotion.add(orderItem.getPromotionAmount());
            intergration = intergration.add(orderItem.getIntegrationAmount());

            //总价
            total = total.add(orderItem.getRealAmount());

            //积分信息和成长值信息
            integrationTotal += orderItem.getGiftIntegration();
            growthTotal += orderItem.getGiftGrowth();

        }
        //1、订单价格相关的
        orderEntity.setTotalAmount(total);
        //设置应付总额(总额+运费)
        orderEntity.setPayAmount(total.add(orderEntity.getFreightAmount()));
        orderEntity.setCouponAmount(coupon);
        orderEntity.setPromotionAmount(promotion);
        orderEntity.setIntegrationAmount(intergration);

        //设置积分成长值信息
        orderEntity.setIntegration(integrationTotal);
        orderEntity.setGrowth(growthTotal);
    }

    private List<OrderItemEntity> createOrderItemEntities(String timeId) {
        R checkedCart = cartFeign.getCheckedCart();
        if (checkedCart.getCode() == 0) {
            List<OrderItemVo> data = checkedCart.getData("data", new TypeReference<List<OrderItemVo>>() {});
            List<OrderItemEntity> orderItemEntities = data.stream().map(orderItemVo -> {
                OrderItemEntity orderItemEntity = createOrderItemEntity(orderItemVo);
                orderItemEntity.setOrderSn(timeId);
                return orderItemEntity;
            }).collect(Collectors.toList());
            return orderItemEntities;
        }
        return null;
    }

    private OrderItemEntity createOrderItemEntity(OrderItemVo orderItemVo) {
        OrderItemEntity orderItemEntity = new OrderItemEntity();
        //设置sku信息
        orderItemEntity.setSkuId(orderItemVo.getSkuId());
        orderItemEntity.setSkuName(orderItemVo.getTitle());
        orderItemEntity.setSkuAttrsVals(StringUtils.collectionToDelimitedString(orderItemVo.getAttrs(),";"));
        orderItemEntity.setSkuPrice(orderItemVo.getPrice());
        orderItemEntity.setSkuQuantity(orderItemVo.getAmount());
        orderItemEntity.setSkuPic(orderItemVo.getSkuImg());
        //设置spu信息
        R entity = productFeign.getSpuEntityWithSkuId(orderItemVo.getSkuId());
        if(entity.getCode()==0){
            SpuInfoVo data = entity.getData("data", new TypeReference<SpuInfoVo>() {});
            orderItemEntity.setSpuBrand(data.getBrandName());
            orderItemEntity.setSpuId(data.getSpuId());
            orderItemEntity.setSpuName(data.getSpuName());
            orderItemEntity.setCategoryId(data.getCatalogId());
        }
        //设置商品的积分信息
        orderItemEntity.setGiftGrowth(orderItemVo.getPrice().multiply(new BigDecimal(orderItemVo.getAmount())).intValue());
        orderItemEntity.setGiftIntegration(orderItemVo.getPrice().multiply(new BigDecimal(orderItemVo.getAmount())).intValue());
        //设置商品的价格信息
        orderItemEntity.setPromotionAmount(BigDecimal.ZERO);
        orderItemEntity.setCouponAmount(BigDecimal.ZERO);
        orderItemEntity.setIntegrationAmount(BigDecimal.ZERO);
        ////当前订单项的实际金额.总额 - 各种优惠价格
        //原来的价格
        BigDecimal origin = orderItemEntity.getSkuPrice().multiply(new BigDecimal(orderItemEntity.getSkuQuantity().toString()));
        //原价减去优惠价得到最终的价格
        BigDecimal subtract = origin.subtract(orderItemEntity.getCouponAmount())
                .subtract(orderItemEntity.getPromotionAmount())
                .subtract(orderItemEntity.getIntegrationAmount());
        orderItemEntity.setRealAmount(subtract);
        return orderItemEntity;
    }

    private OrderEntity createOrderEntity(String timeId) {
        OrderEntity orderEntity = new OrderEntity();
        //获取当前登录用户
        MemberEntity memberEntity = OrderInterceptor.threadLocal.get();
        orderEntity.setMemberId(memberEntity.getId());
        orderEntity.setMemberUsername(memberEntity.getUsername());
        //订单号
        orderEntity.setOrderSn(timeId);

        OrderSubmitVo orderSubmitVo = threadLocal.get();

        R r = memberFeign.getAdddressWithAddrId(orderSubmitVo.getAddrId());
        if(r.getCode()==0){
            //设置收获人信息
            FareVo data = r.getData("data", new TypeReference<FareVo>() {});
            orderEntity.setReceiverName(data.getAddress().getName());
            orderEntity.setReceiverCity(data.getAddress().getCity());
            orderEntity.setReceiverDetailAddress(data.getAddress().getDetailAddress());
            orderEntity.setReceiverName(data.getAddress().getName());
            orderEntity.setReceiverPostCode(data.getAddress().getPostCode());
            orderEntity.setReceiverProvince(data.getAddress().getProvince());
            orderEntity.setReceiverRegion(data.getAddress().getRegion());
            //设置运费信息
            orderEntity.setFreightAmount(data.getFare());
        }
        //设置订单相关的状态信息
        orderEntity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
        orderEntity.setAutoConfirmDay(7);
        orderEntity.setConfirmStatus(0);
        return orderEntity;
    }

}